<template>
  <div style="text-align: center;"><h1 style="color: #4154c7;">新建通知公告</h1></div>
  <div style="margin: 30px;align-content: center">
    <el-form style="margin:0 50px;padding:10px;border:1px solid #c1c1c1;">
      <el-row :gutter="30" type="flex" align="middle">
        <el-col :span="7">
          <el-form-item label="创建人:">
            <el-input readonly :value="user.username" disabled/>
          </el-form-item>
        </el-col>

        <el-col :span="7" style="margin-left: 50px">
          <el-form-item label="创建时间:">
            <!-- 使用v-model绑定表单数据 -->
            <el-date-picker
                v-model="noticeArr.currentDate"
                type="date"
                placeholder="请选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider style="margin:0 0 15px 0"></el-divider>

      <el-row :gutter="30" type="flex" align="middle">
        <el-form-item label="标 题 :" style="margin-left: 15px;width: 710px;">
          <el-input placeholder="请输入公告的标题" v-model="noticeArr.title"/>
        </el-form-item>
      </el-row>

      <el-divider style="margin:0 0 15px 0"></el-divider>

      <el-row :gutter="30" type="flex" align="buttom">
        <el-form-item label="公告类型:" style="margin-left: 15px;">
          <el-select style="width: 240px" v-model="noticeArr.level" placeholder="请选择公告类型">
            <el-option label="紧急" value="3"></el-option>
            <el-option label="重要" value="2"></el-option>
            <el-option label="一般" value="1"></el-option>
            <el-option label="次要" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-divider style="margin:0 0 15px 0"></el-divider>

      <el-row :gutter="30">
        <el-form-item label="发布对象:" style="margin-left: 15px;">
          <!--       层级选择   -->
          <el-select
              v-model="noticeArr.empListId"
              filterable
              multiple
              clearable
              collapse-tags
              placeholder="请选择要发布的对象"
              popper-class="custom-header"
              :max-collapse-tags="1"
              style="width: 240px"
          >
            <template #header>
              <el-checkbox
                  v-model="checkAll"
                  :indeterminate="indeterminate"
                  @change="handleCheckAll"
              >All
              </el-checkbox>
            </template>
            <el-option
                v-for="item in receiveObject"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-row>
      <el-divider style="margin:0 0 15px 0"></el-divider>

      <div style="margin-bottom:5px">
        <label
            style="height:32px;line-height: 32px;font-weight: lighter;font-size: 14px;
            color:#000;">公告内容：</label>
      </div>
      <div style="border: 1px solid #ccc">
        <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            mode="default"
        />
        <Editor
            style="height: 500px; overflow-y: hidden;"
            v-model="noticeArr.content"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleCreatedEditor"
        />
      </div>
    </el-form>

    <el-row :gutter="30" style="margin:15px 50px;">
      <el-button @click="saveNotice" type="primary">发送</el-button>
      <el-button @click="toDrafts" type="success">存草稿</el-button>
      <el-button @click="closeEdit" type="danger">取消</el-button>
    </el-row>

  </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import router from "@/router";
import {onMounted, ref, shallowRef, watchEffect} from "vue";
import qs from "qs";

import {ElMessage} from "element-plus";
import axios from "@/api/axios";

const user = ref(getUser());
//===========================================富文本编辑器===========================================
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const toolbarConfig = {}
const editorConfig = {placeholder: '请输入内容...'}

const handleCreatedEditor = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  noticeArr.value = {};
}

//获取公告详情页 编辑操作 时，跳转页面传递的公告id
const noticeId = new URLSearchParams(window.location.search).get('id');
//保存要发布的内容
const noticeArr = ref({
  noticeId: noticeId,
  createPeopleId: user.value.id,
  // createTime:'',
  currentDate: '',
  title: '',  //标题
  level: '',  //类型
  content: '',    //富文本内容
  status: '',    //公告发布的状态 默认为1-启用
  empListId: [],//已选中的员工列表（发布对象）
});

//Quill编辑器的工具栏配置数组
const toolBarConfig = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],

  [{'header': 1}, {'header': 2}],               // custom button values
  [{'list': 'ordered'}, {'list': 'bullet'}],
  [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
  [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
  [{'direction': 'rtl'}],                         // text direction

  [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
  [{'header': [1, 2, 3, 4, 5, 6, false]}],

  [{'color': []}, {'background': []}],          // dropdown with defaults from theme
  [{'font': []}],
  [{'align': []}],

  ['clean']
  // [{'image': ''}], // 添加图片上传功能
]
const emit = defineEmits(['update:value']);
//内容有变化，就更新内容，将值返回给父组件
watchEffect(() => {
  emit('update:value', noticeArr.value.content)
});


// 假设你已经有了一个Quill编辑器实例，命名为quill
// const quill = new Quill('#editor', { modules: { toolbar: toolBarConfig }, theme: 'snow' });
//
// // 监听图片上传
// quill.root.addEventListener('click', function(event) {
//   if (event.target.classList.contains('ql-image')) {
//     event.preventDefault();
//     const input = document.createElement('input');
//     input.setAttribute('type', 'file');
//     input.setAttribute('accept', 'image/*');
//     input.click();
//
//     input.onchange = function() {
//       const file = input.files[0];
//       const formData = new FormData();
//       formData.append('image', file);
//
//       fetch('/your/upload/image/endpoint', {
//         method: 'POST',
//         body: formData
//       })
//           .then(response => response.json())
//           .then(data => {
//             quill.insertEmbed(quill.getSelection().index, 'image', data.url);
//           })
//           .catch(error => console.error('Error uploading image:', error));
//     };
//   }
// });


//绑定日期时间
// 获取当前日期并格式化
// 使用 ref 初始化日期
const currentDate = ref('');
const getCurrentDate = () => {
  const now = new Date();
  // console.log(formatter(now.getDate(),'YYYY-MM-DD HH:mm:ss'));
  let year = now.getFullYear();
  let month = String(now.getMonth() + 1).padStart(2, '0');
  let day = String(now.getDate()).padStart(2, '0');
  // return `${year}-${month}-${day}`;
  currentDate.value = year + '-' + month + '-' + day;
  console.log(currentDate.value);
};

onMounted(() => {
  getCurrentDate();
  selectStaffList();
  if (noticeId != null) {
    getNotice();  //回显当前公告数据
  }
});

// 发布对象：层级选择
// import type {CheckboxValueType} from 'element-plus';
const checkAll = ref(false)
const indeterminate = ref(false)
const receiveObject = ref([])  //所有员工列表


// watch(receiveObject, (val) => {
//   if (val.length === 0) {
//     checkAll.value = false;
//     indeterminate.value = false;
//   } else if (val.length === cities.value.length) {
//     checkAll.value = true;
//     indeterminate.value = false;
//   } else {
//     indeterminate.value = true;
//   }
// })
const handleCheckAll = (val) => {
  indeterminate.value = false;
  if (val) {
    //receiveObject.value将包含一个由cities.value数组中每个元素的value属性组成的数组。
    receiveObject.value = cities.value.map((_) => _.value);
  } else {
    receiveObject.value = [];
  }
};

//关闭编辑框
const closeEdit = () => {
  if (confirm('关闭后，当前操作将无法保存，确认关闭？')) {
    router.push('/notice');
  }
};
//发送公告
const saveNotice = () => {
  if (confirm('确定要更新发布当前公告吗？')) {
    // noticeArr.value.currentDate = currentDate;
    axios.post('/v1/notice/update', noticeArr.value, {serviceName: 'noticeService'})
        .then((response) => {
          if (response.data.code === 200) {
            ElMessage.success('公告更新成功！');
            router.push('/notice');
          } else {
            ElMessage.error(response.data.msg);
          }
        });
  }
};
//存为草稿
const toDrafts = () => {
  if (confirm('确定要将当前公告存到草稿箱吗？')) {
    noticeArr.value.status = '0';  //存为草稿，公告的发布状态为0
    let data = qs.stringify(noticeArr.value);
    noticeArr.value = [
      {
        index: '1',
        title: 'JetBrains全新UI正式官宣标配！',
        type: '一般',
        status: '未发布',
        createPeople: 'Lisa',
        createTime: '2024-07-20'
      },
      {
        index: '2',
        title: '华为余承东回应「25 亿元转让问让问界」；鸿蒙 PC 版现身华为开发者官网；Linux Kernel 6.10释出 | 极客头条',
        type: '一般',
        status: '未发布',
        createPeople: '李华',
        createTime: '2024-07-19'
      }
    ];
    axios.post('/v1/notice/toDrafts', {serviceName: 'noticeService', params: {noticeArr}})
        .then((response) => {
          if (response.data.code === 200) {
            ElMessage.success('成功保存到草稿箱！');
            router.push('/notice');
          } else {
            ElMessage.error('到草稿箱' + response.data.msg);
          }
        });
  }
};

//回显公告数据
const getNotice = () => {
  // if (noticeId!=null){
  axios.get('/v1/notice/selectInfo/' + noticeId, {serviceName: 'noticeService'}).then((response) => {
    if (response.data.code === 200) {
      ElMessage.success('回显公告数据成功！');
      noticeArr.value = response.data.data;
      console.log('回显数据：');
      console.log(noticeArr.value.content);
    } else {
      ElMessage.error(response.data.msg);
    }
  });
  // }
};

//获取发布对象的下拉列表
const selectStaffList = () => {
  axios.get('/staff/list', {serviceName: 'empService'})
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('查询员工下拉列表成功');
          receiveObject.value = response.data.data;
          console.log('员工列表：');
          console.log(response.data.data);
        } else {
          ElMessage.error('员工下拉列表' + response.data.msg);
        }
      });
};
</script>

<style scoped>
.custom-header {
  .el-checkbox {
    display: flex;
    height: unset;
  }
}
</style>